package top.smallway.lightbandassistant_app.UI;

import static top.smallway.lightbandassistant_app.UI.MainActivity.loginManager;
import static top.smallway.lightbandassistant_app.method.Method.secondsToTimeFormat;
import static top.smallway.lightbandassistant_app.network.Okhttp.uploadkey;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.util.SmartGlideImageLoader;

import top.smallway.lightbandassistant_app.R;
import top.smallway.lightbandassistant_app.data.Song_Data;
import top.smallway.lightbandassistant_app.method.AudioPlayer;

/**
 * 歌曲详情页面
 * 用于显示歌曲的详细信息，包括歌曲名称、作者、时长、BPM、KEY等
 * 提供音频预览和下载功能
 */
public class AboutSong extends AppCompatActivity {
    // 播放器状态常量
    private final int PLAYER_PLAYING = 0;
    private final int PLAYER_STOP = 1;
    // 当前播放器状态
    private int PLAYER_STATIC = PLAYER_STOP;
    // 音频播放器实例
    private final AudioPlayer audioPlayer = new AudioPlayer();
    // 缓存目录
    private final String saveDir = "/storage/emulated/0/Download/lightband_assistant_cache";
    // 歌曲相关信息
    private String song_name, song_author, song_time, song_bpm, song_key, pic_url, previewURL, hash, description;
    // 歌曲封面图片
    private ImageView song_pic;
    // 显示歌曲信息的文本控件
    private TextView TextView_song_name, TextView_song_author, TextView_song_time, TextView_song_bpm, TextView_song_key, TextView_description;
    // 播放和下载按钮
    private Button play, download;
    // 合作者信息
    private JSONArray collaborators;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aboutsong);
        inttview();  //初始化控件
        inttExtra();  //初始化数据
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (PLAYER_STATIC) {
                    case PLAYER_STOP:
                        audioPlayer.setAudioPlayerListener(new AudioPlayer.AudioPlayerListener() {
                            @Override
                            public void onLoadingStarted() {
                                play.setText("正在加载音频");
                            }

                            @Override
                            public void onLoadingComplete() {
                                play.setText("加载完成");
                            }

                            @Override
                            public void onPlayingStarted() {
                                PLAYER_STATIC = PLAYER_PLAYING;
                                play.setText("停止播放");
                            }

                            @Override
                            public void onPlayingStopped() {
                                PLAYER_STATIC = PLAYER_STOP;
                                play.setText("播放音频");
                            }
                        });
                        audioPlayer.playAudio(previewURL);
                        break;
                    case PLAYER_PLAYING:
                        audioPlayer.stopAudio();
                        break;
                }

            }
        });


        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String a = uploadkey(loginManager.getID(), song_key, hash, song_name);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(AboutSong.this, a, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }).start();
            }
        });

    }

    /**
     * 初始化页面视图
     * 绑定布局文件中的控件到对应的变量
     */
    private void inttview() {
        song_pic = findViewById(R.id.song_pic);
        TextView_song_name = findViewById(R.id.song_name);
        TextView_song_author = findViewById(R.id.song_author);
        TextView_song_time = findViewById(R.id.song_time);
        TextView_song_bpm = findViewById(R.id.song_bpm);
        TextView_song_key = findViewById(R.id.song_key);
        play = findViewById(R.id.play);
        download = findViewById(R.id.download);
        TextView_description = findViewById(R.id.description);
    }

    /**
     * 初始化歌曲数据
     * 从Intent中获取歌曲信息并设置到对应的控件
     * 设置各个控件的点击事件，包括：
     * - 作者名点击跳转到作者列表
     * - 描述点击跳转到beatsaver网站
     * - 图片点击查看大图
     * - KEY点击复制到剪贴板
     */
    private void inttExtra() {
        Intent intent = getIntent();
        song_name = intent.getStringExtra("song_name");
        song_author = intent.getStringExtra("song_author");
        song_time = intent.getStringExtra("song_time");
        song_bpm = intent.getStringExtra("song_bpm");
        song_key = intent.getStringExtra("song_key");
        pic_url = intent.getStringExtra("pic_url");
        previewURL = intent.getStringExtra("previewURL");
        hash = intent.getStringExtra("hash");
        description = intent.getStringExtra("description");
        collaborators = JSONArray.parseArray(intent.getStringExtra("collaborators"));

        TextView_song_name.setText(song_name);
        TextView_song_author.setText(song_author);
        TextView_song_author.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AboutSong.this, AuthorList.class);
                intent.putExtra("collaborators", collaborators.toString());
                startActivity(intent);
            }
        });

        TextView_song_time.setText(song_time);
        TextView_song_bpm.setText(song_bpm);
        TextView_song_key.setText("歌曲ID（KEY）\n" + song_key);
        TextView_description.setText(description);
        TextView_description.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://beatsaver.com/maps/" + song_key));
                startActivity(browserIntent);
            }
        });
        Glide.with(this).load(pic_url).placeholder(R.drawable.pgbar).error(R.drawable.loadingerror).into(song_pic);
        song_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XPopup.Builder(AboutSong.this).asImageViewer(song_pic, pic_url, new SmartGlideImageLoader()).show();
            }
        });
        TextView_song_key.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("text", "!bsr " + song_key);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getApplicationContext(), "歌曲KEY已复制", Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * Activity销毁时的回调
     * 重置音频播放器和播放状态
     */
    @Override
    protected void onDestroy() {
        audioPlayer.reset();
        PLAYER_STATIC = PLAYER_STOP;
        super.onDestroy();
    }

    public static Intent fromDataToIntent(Context context, Song_Data song_data){
        Intent intent = new Intent(context, AboutSong.class);

        intent.putExtra("song_name", song_data.getSong_name());
        intent.putExtra("song_author", song_data.getAuthorName());
        intent.putExtra("description", song_data.getSong_description());
        intent.putExtra("song_time", "时长\n" + secondsToTimeFormat(song_data.getDuration()));
        intent.putExtra("song_bpm", "BPM\n" + song_data.getBpm());
        intent.putExtra("song_key", song_data.getSong_id());
        intent.putExtra("pic_url", song_data.getCoverURL());
        intent.putExtra("hash", song_data.getHash());
        intent.putExtra("previewURL", song_data.getPreviewURL());

        return intent;
    }
}